/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.tedu.mall.ams.service.impl;

import cn.tedu.mall.ams.exception.CoolSharkException;
import cn.tedu.mall.ams.mapper.AdminMapper;
import cn.tedu.mall.ams.mapper.AdminRoleMapper;
import cn.tedu.mall.ams.mapper.RoleMapper;
import cn.tedu.mall.ams.service.IRoleService;
import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.admin.dto.RoleAddDTO;
import cn.tedu.mall.common.pojo.admin.dto.RoleQueryDTO;
import cn.tedu.mall.common.pojo.admin.dto.RoleUpdateDTO;
import cn.tedu.mall.common.pojo.admin.model.Role;
import cn.tedu.mall.common.pojo.admin.vo.RoleVO;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.time.Duration;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @since 2021-12-02
 */
@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private AdminMapper adminMapper;

    /* @Autowired
     private AdminMapper adminMapper;*/
    @Override
    public JsonPage<RoleVO> listRoles(
        Integer pageNum,
        Integer sizeNum
    ) {
        PageHelper.startPage(pageNum, sizeNum);
        List<RoleVO> roles = roleMapper.selectRoles();
        PageInfo pageInfo = new PageInfo<>(roles);
        return JsonPage.restPage(pageInfo);
    }

    @Override
    public JsonPage<RoleVO> queryRoles(
        Integer pageNum,
        Integer sizeNum,
        String query
    ) {
        PageHelper.startPage(pageNum, sizeNum);
        List<RoleVO> roles = roleMapper.selectRolesLikeName(query);
        PageInfo pageInfo = new PageInfo<>(roles);
        return JsonPage.restPage(pageInfo);
    }

    @Override
    public void addRole(RoleAddDTO roleAddDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleAddDTO, role);
        roleMapper.insertRole(role);
    }

    @Override
    public void updateRole(RoleUpdateDTO roleUpdateDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateDTO, role);
        roleMapper.updateRole(role);
    }

    @Override
    public void deleteRole(Long id) {
        int exist = roleMapper.selectExistRoleById(id);
        if (exist == 0) {
            throw new CoolSharkException("当前删除的角色不存在:" + id, 409);
        }
        int count = adminRoleMapper.selectRelationByRoleid(id);
        if (count != 0) {
            throw new CoolSharkException("当前角色关联了账号无法删除", 409);
        }
        roleMapper.deleteRol(id);
    }

    @Override
    public JsonPage<RoleVO> queryRoleList(RoleQueryDTO roleQueryDTO) {
        validateQuery(roleQueryDTO);
        PageHelper.startPage(roleQueryDTO.getPage(), roleQueryDTO.getPageSize());
        List<RoleVO> roles = roleMapper.selectRoleByQuery(roleQueryDTO);
        return JsonPage.restPage(new PageInfo<>(roles));
    }

    @Override
    public void enableRole(
        Long id,
        Integer enable
    ) {
        if (enable == 0) {
            //检查当前role是否关联角色，关联则抛出异常
            int count = adminMapper.selectAdminCountByRoleId(id);
            if (count != 0) {
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "当前角色关联了用户，请先停止使用用户");
            }
        }
        roleMapper.updateRoleEnable(id, enable);
    }

    private void validateQuery(RoleQueryDTO roleQueryDTO) {
        //页数为空创建默认
        if (roleQueryDTO.getPage() == null) {
            roleQueryDTO.setPage(1);
        }
        if (roleQueryDTO.getPageSize() == null) {
            roleQueryDTO.setPageSize(5);
        }
        //日期校验
        if (roleQueryDTO.getStartCreateTime() != null && roleQueryDTO.getEndCreateTime() != null) {
            Duration between = Duration.between(roleQueryDTO.getStartCreateTime(), roleQueryDTO.getEndCreateTime());
            long l = between.toMillis();
            if (l < 0) {
                //说明结束时间小于起始时间
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "结束创建时间不能小于起始创建时间");
            }
        }
        //日期校验
        if (roleQueryDTO.getStartModifiedTime() != null && roleQueryDTO.getEndModifiedTime() != null) {
            Duration between = Duration.between(roleQueryDTO.getStartModifiedTime(), roleQueryDTO.getEndModifiedTime());
            long l = between.toMillis();
            if (l < 0) {
                //说明结束时间小于起始时间
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "结束修改时间不能小于起始修改时间");
            }
        }
        //排序
        if (roleQueryDTO.getOrderRule() == null) {
            roleQueryDTO.setOrderRule("desc");
        } else {
            String orderRule = roleQueryDTO.getOrderRule();
            if (!(orderRule.equals("desc") || orderRule.equals("asc"))) {
                throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST, "您的排序规则传递错误,请表达desc 或者 asc");
            }
        }
    }
}
